package edu.alaska.uaa.cs401.fgm;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.prefs.Preferences;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

import net.strudelline.fanorona.FanoronaGameBoardFrame;
import net.strudelline.fanorona.FanoronaJoaAI;
import net.strudelline.fanorona.FanoronaRandomAI;

/**
 * 
 * @author James AND MATT!! YAY
 * 
 * Tests
 * 
 * When the UI opens, a server should be spawned capable of accepting two TCP connections
 * which will then manipulate the internal game board which will also display on the screen
 * whenever a change is made.  THE END
 * oh it'll say "white wins" or "black wins" when one wins.
 *
 */

public class FanoronaServerFrame extends JFrame implements FanoronaBoardDisplayerInterface {
	/**
	 * 
	 */
	private static final long serialVersionUID = 959419514198549359L;
	private final int FRAMEW = 500;
	private final int FRAMEH = 500;
	final JPanel mainPanel = new JPanel(new BorderLayout());
	final JTextPane textPane = new JTextPane();
	private JScrollPane scroller = new JScrollPane(textPane);
	//final JTextPane boardPane = new JTextPane(); // for the pieces
	FanoronaGameBoardFrame boardPane = null;// = new FanoronaGameBoardFrame();


	FanoronaBoardInterface board = new FanoronaLinkBoard();
	FanoronaServer server = null;
    Preferences prefs = Preferences.userNodeForPackage(this.getClass());
	
	public FanoronaServerFrame()
	{
//		String loggingDirectory = prefs.get("loggingDirectory", null);
//		if (loggingDirectory == null) {
//			JFileChooser chooser = new JFileChooser();
//			chooser.show
//		}
		
		
		setTitle("Fanorona Server");
		setSize(FRAMEW, FRAMEH);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	
		
		//boardPane.setFont(new Font("Courier", Font.PLAIN,14));
		//boardPane.setMinimumSize(new Dimension(11,7));
		//boardPane.
		boardPane = new FanoronaGameBoardFrame();
		Container contentPane = getContentPane();
		textPane.setText("Welcome!");
		//contentPane.add(textPane, "Center");
		mainPanel.add(scroller,BorderLayout.CENTER);
		mainPanel.add(boardPane,BorderLayout.NORTH);
		//mainPanel.add(textPane,BorderLayout.CENTER);
		setContentPane(mainPanel);
		//boardPane.setEditable(false);
		textPane.setEditable(false);
		
		JPanel buttonBar = new JPanel();
		JButton randomAI = new JButton("start random bot");
		randomAI.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				FanoronaRandomAI ai = new FanoronaRandomAI("localhost",3266);
				new Thread(ai).start();
			}			
		});
		buttonBar.add(randomAI);
		JButton joaAI = new JButton("start todd");
		joaAI.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				FanoronaJoaAI ai = new FanoronaJoaAI("localhost",3266);
				new Thread(ai).start();
			}			
		});
		buttonBar.add(joaAI);
		mainPanel.add(buttonBar,"South");

	}
	public FanoronaServerFrame setServer(FanoronaServer server) {
		this.server = server;
		server.setDisplayer(this);
		return this;
	}
	
	private static <T> String join(Collection<T> lin,String joiner) {
		LinkedList<T> l = new LinkedList<T>();
		l.addAll(lin);
		StringBuilder bb = new StringBuilder();
		while (l.size() > 1) {
			bb.append(l.remove(0).toString());
			bb.append(joiner);
		}
		bb.append(l.get(0));
		return bb.toString();
	}
	
	private static <T> String join(Iterable<T> lin,String joiner) {
		LinkedList<T> l = new LinkedList<T>();
		for (T i : lin) l.add(i);
		return join(l,joiner);
	}
	
	public void update() {
		try {
			EventQueue.invokeAndWait(new Runnable() {
				public void run() {
					//String boardtext = "";
					
					//System.out.println("updating");
					//FanoronaBoardInterface b = server.getBoard();

//				if (b == null) {
//					boardtext = "No game in progress\n\n\n\n";
//				} else {
//					List<String> lines = new LinkedList<String>();
//					lines.add(" |012345678");
//					lines.add("-----------");
//					String sb = server.getBoard().stringBoard();
//					String [] sbs = sb.split("\n");
//					int i = 4;
//					for (String line : sbs) {
//						lines.add(String.format("%d|%s",i--,line));
//					}
//					boardtext = join(lines,"\n");
//
//				}

					textPane.setText(join(server.getStatusArray(FanoronaServer.StatusPriority.HIGH),"\n"));
					//boardPane.setText(boardtext);
					boardPane.setBoard(server.getBoard());
				}
			});
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	static public void main(String[] args) {
		final FanoronaServerFrame f;
		try {
			FanoronaServer s = new FanoronaServer();
			s.setDaemon(true);
			s.start();
			
			s.setLoggingDirectory(".");
			
			f = new FanoronaServerFrame().setServer(s);
			// K constant
			// K kinetic motion of fanorona pieces as I destroy game
			// K^12 <-- big number
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					f.setVisible(true); // can't do this from the main thread.
				}
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.err.format("Unable to start server!\n");
			e.printStackTrace();
			System.exit(1);
		}
	}
	public String requestNewLogFile() {
		return null;
		// if the file fails to save, this should pop up a new message requesting a new
		// filename
	}
}
